import time
from os import path
from lxml import etree

import yaml

from view.ths_view.simulated_view import SimulatedView
from appium.webdriver.common.appiumby import AppiumBy
from common import logger

"""
ths A股实盘账户页
"""


class AshareView(SimulatedView):
    # A股tab下元素
    # 第一个账号
    a_frist_account = (AppiumBy.ID, "com.hexin.plat.android:id/frontview_account_info")
    # a_frist_account = (AppiumBy.XPATH,
    #                    "//android.widget.RelativeLayout[@resource-id='com.hexin.plat.android:id/frontview_account_info']")
    # 输入密码弹窗关闭按钮
    a_close_button = (AppiumBy.ID, "com.hexin.plat.android:id/close_button")
    # 输入交易密码
    a_input_pw = (AppiumBy.ID, "com.hexin.plat.android:id/weituo_edit_trade_password")
    # 登录按钮
    a_login_button = (AppiumBy.ID, "com.hexin.plat.android:id/weituo_btn_login")

    def login(self):
        """
        登录A股实盘账户
        :return:
        """
        # 检查输入弹窗是否弹出
        if self.check_a_input():
            pass
        else:
            self.find_element(self.a_frist_account).click()
        time.sleep(2)
        udid = self.driver.capabilities['desired']['udid']
        with open('C:\\Sourcetree\\GProject\\real_trading\\run_daily\\device_account_mapping.yaml', 'r',
                  encoding='utf-8') as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
        if not data[udid]:
            raise Exception("device_account_mapping.yaml中没有找到对应的实盘账户！")
        self.input_number(data[udid]['password'])
        self.find_element(self.a_login_button).click()

    def check_a_input(self):
        """
        检查A股账号输入弹窗
        :return:
        """
        a_zh_btn = self.find_element_by_wait(self.a_close_button, timeout=2)
        if a_zh_btn:
            return True

    def enter_ashare_buy(self):
        """
        首次启动设备后首先进入的准备页面
        进入实盘买入页面
        :return:
        """
        # 广告页跳过
        # self.check_skip_btn()
        # 弹窗关闭
        self.check_close_btn()
        # 点击交易进入交易页面
        self.click_transaction_tab()
        # 输入密码点击登录
        self.login()
        time.sleep(3)
        logger.info("到了总资产页")
        # 下拉回去
        # self.swipe_down_half()
        # # 点击买入
        self.click_buy_menu()
